package com.dhcy.mqtt.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhcy.mqtt.dao.EquipmentMapper;
import com.dhcy.mqtt.dao.OnlineDataMapper;
import com.dhcy.mqtt.model.Equipment;
import com.dhcy.mqtt.model.OnlineData;
import com.dhcy.mqtt.par.ht.EquipmentDataPar;
import com.dhcy.mqtt.par.ht.HandleDto;
import com.dhcy.mqtt.par.ht.OnlineDataPar;
import com.dhcy.mqtt.result.ht.OnlineDataResult;
import com.dhcy.mqtt.result.ht.TableResultData;
import com.dhcy.mqtt.service.AsynService;
import com.dhcy.mqtt.service.OnlineDataService;
import com.dhcy.mqtt.util.AppResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional
public class OnlineDataServiceImpl extends ServiceImpl<OnlineDataMapper, OnlineData> implements OnlineDataService {

    @Autowired
    private OnlineDataMapper onlineDataMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    AsynService asynService;

    /**
     * 订阅数据处理
     * @param json
     */
    @Override
    public void add(String json) {
        JSONObject parseObj = JSONUtil.parseObj(json);
        OnlineData onlineData = JSONUtil.toBean(parseObj, OnlineData.class);
        if (ObjectUtil.isNotEmpty(onlineData.getDeviceNumber())){
            Equipment equipment = equipmentMapper.selectOne(new QueryWrapper<Equipment>().eq("number", onlineData.getDeviceNumber()).eq("is_del", 0));
            if (ObjectUtil.isEmpty(equipment)){
                Equipment equipment1 = new Equipment();
                equipment1.setNumber(onlineData.getDeviceNumber());
                equipment1.setCreateTime(new Date());
                equipmentMapper.insert(equipment1);
            }
        }
        onlineData.setCreateTime(new Date());
        onlineDataMapper.insert(onlineData);
    }

    /**
     * 数据列表
     * @param pagePar
     * @return
     */
    @Override
    public TableResultData list(OnlineDataPar pagePar) {
        IPage<OnlineData> page = new Page<>(pagePar.getPage(), pagePar.getPageSize());
        IPage<OnlineDataResult> onlineDataResultIPage = onlineDataMapper.queryList(page, pagePar.getNumber());
        return TableResultData.success(onlineDataResultIPage.getTotal(), onlineDataResultIPage.getRecords());
    }

    @Override
    public AppResultData brokenLine(Integer num,String number) {
        if (ObjectUtil.isEmpty(num) || 0 >= num){
            num = 10;
        }
        QueryWrapper<OnlineData> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("limit "+num);
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("device_number",number);
        List<OnlineData> onlineData = onlineDataMapper.selectList(queryWrapper);
        Collections.reverse(onlineData);
        return AppResultData.successData(onlineData);
    }

    /**
     * 接受数据
     * @param equipmentDataPar
     */
    @Override
    public void addData(EquipmentDataPar equipmentDataPar) {
        JSONObject jsonObject = JSONUtil.parseObj(equipmentDataPar.getMsg());
//        log.error("接收到数据：{}",JSONUtil.toJsonStr(jsonObject));
//        JSONObject msg = jsonObject.getJSONObject("msg");
        String devId = jsonObject.getStr("dev_id");
        if (ObjectUtil.isNotEmpty(devId)){
            Equipment equipment = equipmentMapper.selectOne(new QueryWrapper<Equipment>().eq("number", devId).eq("is_del", 0));
            if (ObjectUtil.isEmpty(equipment)){
                Equipment equipment1 = new Equipment();
                equipment1.setNumber(devId);
                equipment1.setCreateTime(new Date());
                //标识注册
                HandleDto handleDto = new HandleDto(){{
                    setDeviceNumber(devId);
                }};
                asynService.regIden(handleDto,1);
//                equipmentMapper.insert(equipment1);
            }
        }
        JSONObject value = jsonObject.getJSONObject("value");
        if (ObjectUtil.isNotEmpty(value)){
            HandleDto handleDto = new HandleDto(){{
                setCh4(devide(value.getDouble("S3_CH4")));
                setCo(devide(value.getDouble("S1_CO")));
                setH2s(devide(value.getDouble("S2_H2S")));
                setO2(devide(value.getDouble("S4_O2")));
                setHumidity(value.getStr("air_rh"));
                setTemperature(value.getStr("air_t"));
                setDeviceNumber(devId);
            }};
            asynService.regIden(handleDto,2);
//            OnlineData onlineData = new OnlineData();
//            onlineData.setCo(value.getStr("S1_CO"));
//            onlineData.setCo(value.getStr("S1_CO"));
//            onlineData.setH2s(value.getStr("S2_H2S"));
//            onlineData.setO2(value.getStr("S4_O2"));
//            onlineData.setTemperature(value.getStr("air_t"));
//            onlineData.setDeviceNumber(devId);
////        BeanUtils.copyProperties(equipmentDataPar,onlineData);
//            onlineData.setCreateTime(new Date());
//            onlineDataMapper.insert(onlineData);
        }

    }

    public String devide(Double num){
        return new BigDecimal(num).divide(new BigDecimal(10)).setScale(2).toString();
    }
}
